package org.example.controller;

import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.example.entity.User;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    @Autowired
    private UserService userService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @GetMapping("/test")
    public String test() {
        userService.save(new User("1", "test", "test"));
        return "test:user";
    }
    @GetMapping("/testOpenFeign")
    public String testOpenFeign() {
        return "OpenFeign";
    }
    @GetMapping("/sendMsg")
    public String sendMsg() {
        SendResult sendResult = rocketMQTemplate.syncSend("cloud3:tagA", "sync");
        SendStatus sendStatus = sendResult.getSendStatus();
        System.out.println(sendStatus);
        return "success";
    }
    @GetMapping("/asyncSendMsg")
    public String asyncSendMsg() {
        rocketMQTemplate.asyncSend("cloud3:tagB", "async", new SendCallback() {

            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("成功" + sendResult);
            }

            @Override
            public void onException(Throwable throwable) {
                throwable.printStackTrace();
            }
        });
        return "success";
    }
    @GetMapping("/oneWay")
    public String oneWay() {
        rocketMQTemplate.sendOneWay("cloud3:tagC", "one way");
        return "success";
    }
    @GetMapping("/delayed")
    public String delayed() {
        // 构建消息对象
        Message<String> message = MessageBuilder.withPayload("我是一个延迟消息").build();
        // 发送一个延时消息，延迟等级为4级，也就是30s后被监听消费
        SendResult sendResult = rocketMQTemplate.syncSend("cloud3", message, 2000, 4);
        System.out.println(sendResult.getSendStatus());
        return "success";
    }
    @GetMapping("/order")
    public String order() {
        for (int i = 0; i < 10; i++) {
            Message<String> message = MessageBuilder.withPayload("我是一个顺序消息"+i).build();
            rocketMQTemplate.syncSendOrderly("cloud3",message,"order");
        }
        return "success";
    }
}
